//
//  STAttributedStringController.swift
//  iPhone
//
//  Created by Toj on 3/28/23.
//

import UIKit

// MARK: - 懒加载(属性), 变量, 初始化init
class STAttributedStringController: UIViewController {
    
    private let inset = 16.ui_scale
    
    private let buttonSize = CGSize(width: 150, height: 44)
    private let buttonSize2 = CGSize(width: CGFloat.dv_width - 32, height: 44)
    private lazy var htmlButton: UIButton = {
        let view = UIButton()
        view.backgroundColor = .white
        view.setTitle("HTML", for: .normal)
        view.setTitleColor(.red, for: .normal)
        view.addTarget(self, action: #selector(didTapShowHtmlText), for: .touchUpInside)
        
        view.frame = CGRect(origin: .zero, size: buttonSize)
        let radius = view.frame.height * 0.5
        view.cm_shadow(color: UIColor.red, opacity: 0.5, radius: 3, offset: CGSize(width: 0, height: -5), corner: radius)
        
        return view
    }()
    
    private lazy var htmlLabel: UILabel = {
        let view = UILabel()
        view.numberOfLines = 0
        view.backgroundColor = .red
        return view
    }()
  
    private lazy var htmlCopyLabel: UILabel = {
        let view = UILabel()
        view.numberOfLines = 0
        view.backgroundColor = .blue
        return view
    }()
    
    private lazy var attributedButton: UIButton = {
        let view = UIButton()
        
        view.titleLabel?.font = 14.to_rbtBoldFont
        view.setTitle("BUY NOW", for: .normal)
        view.setTitleColor("#775E33".to_color, for: .normal)
        view.adjustsImageWhenHighlighted = false
        view.addTarget(self, action: #selector(didTapAttributedText), for: .touchUpInside)
        
        // 阴影
        view.frame = CGRect(origin: .zero, size: buttonSize2)
        let radius = view.frame.height * 0.5
        view.st_shadow(corner: radius)
        
        // 边框
        // view.st_borderColor = "#D7B971".to_color
        
        // 渐变 + 圆角
        let colors2 = ["#F5DB9D", "#E8CD8C"]
        let colors: [UIColor] = [.random, .random]
        let image = UIImage.gd_image(
            gradient: colors2,
            size: view.frame.size,
            corner: radius,
            borderColor: "#D7B971".to_color,
            borderWidth: 1
        )
        view.setBackgroundImage(image, for: .normal)
        
        return view
    }()
    
    private lazy var attributedLabel: UILabel = {
        let view = UILabel()
        view.numberOfLines = 0
//        view.backgroundColor = .red
        return view
    }()
    
    private lazy var attributedLabel2: UILabel = {
        let view = UILabel()
        view.numberOfLines = 0
        return view
    }()
    
    private lazy var attributedLabel3: UILabel = {
        let view = UILabel()
        view.numberOfLines = 0
        return view
    }()
    
    private lazy var attributedLabel4: UILabel = {
        let view = UILabel()
        view.numberOfLines = 0
        return view
    }()
    
    private lazy var attributedLabel5: UILabel = {
        let view = UILabel()
        view.numberOfLines = 0
        return view
    }()
    
    private lazy var attributedLabel6: UILabel = {
        let view = UILabel()
        view.numberOfLines = 0
        return view
    }()
    
    private lazy var htmls: [String] = {
        let width = CGFloat.sr_width - inset * 2
        let texts = [
            "<ul class=\" list-paddingleft-2\" style=\"list-style-type: disc;\"><li><span><strong>Only ₦144/Day.&nbsp;</strong></span></li><li><span>Access to <strong>All Channel&amp;VODs</strong>, Unlimited for <strong>7 Days</strong>, <strong>UEL, FA Cup, Copa del Rey, Bundesliga</strong>, NBA, MLS, Turkish League, Coppa Italia, AMC Movies, Starlife, Fox, Colors.</span></li></ul>",
            "<ul class=\" list-paddingleft-2\" style=\"list-style-type: disc;\"><li><span>Access to</span></li></ul>",
            "Unlimited for&amp; Channel&amp;,hannel&amp;, FA FA Cup, Copa del Rey, BundesligaUnlimited for&amp; Channel&amp;,hannelUnlimited for&amp; Channel&amp;,hannel&amp;, FA FA Cup, Copa del Rey, BundesligaUnlimited for&amp; Channel&amp;,hannelUnlimited for&amp; Channel&amp;,hannel&amp;, FA FA Cup, Copa del Rey, BundesligaUnlimited for&amp; Channel&amp;,hannelUnlimited for&amp; Channel&amp;,hannel&amp;, FA FA Cup, Copa del Rey, BundesligaUnlimited for&amp; Channel&amp;,hannel1234",
            "<ul><li><span>Access to</span></li><li><span>Access to</span></li><li><span>Access to</span></li><li><span>Access to</span></li></ul>",
            "<ul class=\" list-paddingleft-2\" style=\"width: \(width*2)px; white-space: normal;\"><li><span><strong>Only ₦144/Day.&nbsp;</strong></span></li></ul>"
        ]
        
        return texts
    }()
}

// MARK: - 生命周期
extension STAttributedStringController {
    
    override var view: UIView! {
        set {
            super.view = newValue
            CM.begin(time: st_objectName)
        }
        get { return super.view }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupMakeAddSubviews()
        setupMakeLayoutSubviews()
        setupMakeInitialize()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        _ = CM.end(time: st_objectName)
    }
}

// MARK: - 点击事件
@objc private extension STAttributedStringController {
    
    func didTapShowHtmlText() {
        let width = CGFloat.sr_width - inset * 2
        
        let htmlCount = UInt32(htmls.count)
        let htmlRandom = Int(arc4random_uniform(htmlCount))
        var text = htmls[htmlRandom]
        text.st_removeLast(string:"<span><br></span>")
        
        var attributedText: NSAttributedString?
        
        var specHeight = CGFloat.zero
        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html]
        if text.count > 0,
           let data = text.data(using: .unicode, allowLossyConversion: true),
           let attrStr = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil) {
            let range = NSRange(location: 0, length: attrStr.length)
            attrStr.addAttributes([.font: 12.f_scale.to_systemFont], range: range)
            attributedText = attrStr
            specHeight = attrStr.cm_stringHeight(maxWidth: width)
            print("-->toj: html size:\(specHeight)")
        }
        
        htmlLabel.attributedText = attributedText
        
        htmlCopyLabel.attributedText = attributedText
        htmlCopyLabel.sizeToFit()
        print("-->toj: html copy size:\(htmlCopyLabel.frame.size)")
    }
    
    func didTapAttributedText() {
        let attributedString = "Terms of     Service"
        let font = UIFont.systemFont(ofSize: 14)
        let titleColor = UIColor(hex: "#0087EB")
        let backgroundColor = UIColor.blue
        var attributedStringKeys: [NSAttributedString.Key: Any] = [:]
        var underline = 0
        var attributedText: NSAttributedString?
        
        // 1. foregroundColor, font, backgroundColor, ligature, kern
        underline =
        NSUnderlineStyle.thick.rawValue
        attributedStringKeys = [
            .foregroundColor: titleColor,
            .font: font,
            //.backgroundColor: backgroundColor,
            //.ligature: 2, // 设置连体属性
            // .kern: 2 // 设定字符间距
            //    .strikethroughStyle: 1, // 设置删除线
            //.strikethroughColor: UIColor.green,
            //.underlineStyle:
            //[NSUnderlineStyle.single, NSUnderlineStyle.byWord]
                .underlineColor: UIColor.red,
                .underlineStyle: underline
        ]
        
        attributedText = NSMutableAttributedString(string: attributedString, attributes: attributedStringKeys)
        attributedLabel.attributedText  = attributedText
         
        // 2. foregroundColor, font, backgroundColor
        underline =
        NSUnderlineStyle.single.rawValue |
        NSUnderlineStyle.double.rawValue
        attributedStringKeys = [
            .foregroundColor: titleColor,
            .font: font,
            //.strikethroughStyle: 1, // 设置删除线
            .underlineColor: UIColor.red,
            .underlineStyle: underline
        ]
        attributedText = NSMutableAttributedString(string: attributedString, attributes: attributedStringKeys)
        attributedLabel2.attributedText = attributedText
        
        // 3. foregroundColor, font, backgroundColor, ligature
        underline =
        NSUnderlineStyle.single.rawValue |
        NSUnderlineStyle.patternDot.rawValue
        attributedStringKeys = [
            .foregroundColor: titleColor,
            .font: font,
            .underlineColor: UIColor.red,
            .underlineStyle: underline
        ]
        attributedText = NSMutableAttributedString(string: attributedString, attributes: attributedStringKeys)
        attributedLabel3.attributedText = attributedText
        
        // 4. foregroundColor, font, backgroundColor, ligature, kern
        underline =
        NSUnderlineStyle.single.rawValue |
        NSUnderlineStyle.patternDash.rawValue
        attributedStringKeys = [
            .foregroundColor: titleColor,
            .font: font,
            .underlineColor: UIColor.red,
            .underlineStyle: underline
        ]
        attributedText = NSMutableAttributedString(string: attributedString, attributes: attributedStringKeys)
        attributedLabel4.attributedText = attributedText
        
        // 5. foregroundColor, font, backgroundColor, ligature, kern
        underline =
        NSUnderlineStyle.single.rawValue |
        NSUnderlineStyle.patternDashDot.rawValue
        attributedStringKeys = [
            .foregroundColor: titleColor,
            .font: font,
            .underlineColor: UIColor.red,
            .underlineStyle: underline
        ]
        attributedText = NSMutableAttributedString(string: attributedString, attributes: attributedStringKeys)
        attributedLabel5.attributedText = attributedText
        
        // 6. foregroundColor, font, backgroundColor, ligature, kern
        underline =
        NSUnderlineStyle.single.rawValue |
        NSUnderlineStyle.patternDashDotDot.rawValue
        attributedStringKeys = [
            .foregroundColor: titleColor,
            .font: font,
            .underlineColor: UIColor.red,
            .underlineStyle: underline
        ]
        attributedText = NSMutableAttributedString(string: attributedString, attributes: attributedStringKeys)
        attributedLabel6.attributedText = attributedText
    }
}

// MARK: - 初始化设置
private extension STAttributedStringController {
    
    func setupMakeAddSubviews() {
         
        view.addSubview(htmlLabel)
        view.addSubview(htmlCopyLabel)
        view.addSubview(htmlButton)
        view.addSubview(attributedButton)
        
        let labels = [attributedLabel,
                      attributedLabel2,
                      attributedLabel3,
                      attributedLabel4,
                      attributedLabel5,
                      attributedLabel6]
        labels.forEach { view.addSubview($0) }
    }
    
    func setupMakeLayoutSubviews() {
        let spacing = 20.to_cgfloat
        
        var frame = htmlButton.frame
        frame.origin.x = (CGFloat.dv_width - frame.size.width * 2 - spacing) * 0.5
        frame.origin.y = (CGFloat.dv_height - frame.size.height) * 0.5
        htmlButton.frame = frame
        
        frame = attributedButton.frame
        frame.origin.x = (CGFloat.dv_width - frame.size.width) * 0.5
        frame.origin.y = htmlButton.frame.maxY + 10
        attributedButton.frame = frame
        
        htmlLabel.snp.makeConstraints { make in
            make.top.equalTo(CGFloat.nav_barFullHeight+5)
            make.left.right.equalToSuperview().inset(inset)
        }
        
        htmlCopyLabel.snp.makeConstraints { make in
            make.bottom.equalToSuperview().inset(5)
            make.left.right.equalTo(htmlLabel)
        }
        
        var refer = htmlLabel
        var labels = [attributedLabel, attributedLabel2, attributedLabel3]
        labels.forEach { label in
            label.snp.makeConstraints { make in
                make.top.equalTo(refer.snp.bottom).offset(5)
                make.left.right.equalTo(htmlLabel)
            }
            refer = label
        }
        
        refer = htmlCopyLabel
        labels = [attributedLabel4, attributedLabel5, attributedLabel6]
        labels.forEach { label in
            label.snp.makeConstraints { make in
                make.bottom.equalTo(refer.snp.top).offset(-5)
                make.left.right.equalTo(htmlLabel)
            }
            refer = label
        }
    }
    
    func setupMakeInitialize() {
        navigationController?.setNavigationBarHidden(false, animated: false)
        view.backgroundColor = .white
    }
}
